﻿using System;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using KPIS.GERP.GFMS.APP.App_UI.Commons;
using KPIS.GERP.GFMS.IBLL;
using KPIS.GERP.GFMS.BLL;
using KPIS.GERP.GFMS.MODEL;

namespace KPIS.GERP.GFMS.APP.App_UI.UserControls
{
    public partial class FIM_MoneyRequestDtls : System.Web.UI.UserControl
    {
        Main main = new Main();
        IBLL_FIM_MoneyRequests mr = new B_FIM_MoneyRequests();
        IBLL_FIM_MoneyRequestDtls mrd = new B_FIM_MoneyRequestDtls();
        IBLL_BGM_MAS_Source source = new B_BGM_MAS_Source();
        IBLL_BGM_MAS_Expense exp = new B_BGM_MAS_Expense();
        //IBLL_FIM_MAS_Currencies cur = new B_FIM_MAS_Currencies();
        string _strMoneyReqSeq;
        string _strBgmSourceSeq;
        string _strBgmYear;
        string _strBgmProjOperSeq;
        string _strBgmExpGrpSeq;
        string _strJobsiteSeq;
        string _strEventSeq;

        protected void Page_Load(object sender, EventArgs e)
        {
            SumAmount();
        }

        public void LoadRoot(string strMoneyReqSeq, string strBgmSourceSeq
            , string strBgmYear, string strEventSeq, string strBgmProjOperSeq
            , string strBgmExpGrpSeq, string strJobsiteSeq, bool bHaveTax)
        {
            _strMoneyReqSeq = strMoneyReqSeq;
            _strBgmSourceSeq = strBgmSourceSeq;
            _strBgmYear = strBgmYear;
            _strEventSeq = strEventSeq;
            _strBgmProjOperSeq = strBgmProjOperSeq;
            _strBgmExpGrpSeq = strBgmExpGrpSeq;
            _strJobsiteSeq = strJobsiteSeq;

            LoadGrdFimMoneyReqDtls();
            PanelPercentTax.Visible = bHaveTax;
            //PanelTax.Visible = bHaveTax;
            grdFimMoneyReqDtls.Columns.FindByUniqueName("vat").Visible = bHaveTax;
            grdFimMoneyReqDtls.Columns.FindByUniqueName("tax").Visible = bHaveTax;

            SumAmount();
        }

        public void LoadGrdFimMoneyReqDtls()
        {
            IList<M_FIM_MoneyRequestDtls> infoList = mrd.GetExpFromProject(_strBgmProjOperSeq
                , _strBgmSourceSeq, _strBgmExpGrpSeq, _strMoneyReqSeq);
            grdFimMoneyReqDtls.DataSource = infoList;
            grdFimMoneyReqDtls.DataBind();

            if (infoList.Count > 0)
            {
                txtPercentVat.Text = infoList[0].percent_vat.ToString();
                txtPercentTax.Text = infoList[0].percent_tax.ToString();
            }
            else
            {
                txtPercentVat.Text = main.GetSystemControls().default_vat_rate.ToString();
                txtPercentTax.Text = main.GetSystemControls().default_tax_rate.ToString();
            }
        }

        public RadGrid GetGrid()
        {
            return grdFimMoneyReqDtls;
        }

        //protected IList<M_FIM_MAS_Currencies> LoadDDLCurrencySeq()
        //{
        //    return cur.GetList();
        //}

        protected void SumAmount()
        {
            double dAmount = 0;
            //double dExchangeRate = 0;
            //double dBathAmount = 0;
            double dSumBathAmount = 0;

            RadNumericTextBox txtAmount = null;
            //RadNumericTextBox txtExchangeRate = null;
            //RadNumericTextBox txtBathAmount = null;
            RadNumericTextBox txtFooterBathAmount = null;
            GridItem[] Footer = grdFimMoneyReqDtls.MasterTableView.GetItems(GridItemType.Footer);

            if (Footer.Length > 0)
            {
                txtFooterBathAmount = (RadNumericTextBox)Footer[0].FindControl("txtFooterBathAmount");
            }
            else
            {
                return;
            }

            for (int i = 0; i < grdFimMoneyReqDtls.Items.Count; i++)
            {
                txtAmount = (RadNumericTextBox)grdFimMoneyReqDtls.Items[i]["amount"].FindControl("txtAmount");
                //txtExchangeRate = (RadNumericTextBox)grdFimMoneyReqDtls.Items[i]["exchange_rate"].FindControl("txtExchangeRate");
                //txtBathAmount = (RadNumericTextBox)grdFimMoneyReqDtls.Items[i]["bath_amount"].FindControl("txtBathAmount");

                if (txtAmount.Text.Length > 0)
                    dAmount = Convert.ToDouble(txtAmount.Text);
                else
                    dAmount = 0;

                //if (txtExchangeRate.Text.Length > 0)
                //    dExchangeRate = Convert.ToDouble(txtExchangeRate.Text);
                //else
                //    dExchangeRate = 0;

                //dBathAmount = dAmount * dExchangeRate;
                //txtBathAmount.Text = dBathAmount.ToString();
                dSumBathAmount += dAmount;
            }

            txtFooterBathAmount.Value = dSumBathAmount;

            if (PanelPercentTax.Visible)
            {
                SumTax();
            }
        }

        protected void SumTax()
        {
            double dVatAmount = 0;
            double dTaxAmount = 0;
            double dSumVatAmount = 0;
            double dSumTaxAmount = 0;

            RadNumericTextBox txtVatAmount = null;
            RadNumericTextBox txtTaxAmount = null;
            RadNumericTextBox txtFooterVatAmount = null;
            RadNumericTextBox txtFooterTaxAmount = null;
            GridItem[] Footer = grdFimMoneyReqDtls.MasterTableView.GetItems(GridItemType.Footer);

            if (Footer.Length > 0)
            {
                txtFooterVatAmount = (RadNumericTextBox)Footer[0].FindControl("txtFooterVatAmount");
                txtFooterTaxAmount = (RadNumericTextBox)Footer[0].FindControl("txtFooterTaxAmount");
            }
            else
            {
                return;
            }

            for (int i = 0; i < grdFimMoneyReqDtls.Items.Count; i++)
            {
                txtVatAmount = (RadNumericTextBox)grdFimMoneyReqDtls.Items[i]["vat"].FindControl("txtAmountVat");
                txtTaxAmount = (RadNumericTextBox)grdFimMoneyReqDtls.Items[i]["tax"].FindControl("txtAmountTax");

                if (txtVatAmount.Text.Length > 0)
                    dVatAmount = Convert.ToDouble(txtVatAmount.Text);
                else
                    dVatAmount = 0;

                if (txtTaxAmount.Text.Length > 0)
                    dTaxAmount = Convert.ToDouble(txtTaxAmount.Text);
                else
                    dTaxAmount = 0;

                dSumVatAmount += dVatAmount;
                dSumTaxAmount += dTaxAmount;
            }

            txtFooterVatAmount.Value = dSumVatAmount;
            txtFooterTaxAmount.Value = dSumTaxAmount;
        }

        protected void grdFimMoneyReqDtls_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridDataItem)
            {
                GridDataItem dataItem = (GridDataItem)e.Item;
                RadNumericTextBox txtAmount = (RadNumericTextBox)dataItem["amount"].FindControl("txtAmount");
                //RadNumericTextBox txtExchangeRate = (RadNumericTextBox)dataItem["exchange_rate"].FindControl("txtExchangeRate");
                //RadNumericTextBox txtBathAmount = (RadNumericTextBox)dataItem["bath_amount"].FindControl("txtBathAmount");
                RadNumericTextBox txtAmountVat = (RadNumericTextBox)dataItem["vat"].FindControl("txtAmountVat");
                RadNumericTextBox txtAmountTax = (RadNumericTextBox)dataItem["tax"].FindControl("txtAmountTax");
                ImageButton cmdExpRate = (ImageButton)dataItem["amount"].FindControl("cmdExpRate");
                string strExpRateCount = main.WebString(dataItem["m_bgm_projectoperationexpense.m_bgm_projectexpense.m_bgm_mas_expense.exp_rate_count"].Text);
                int nExpRateCount = Convert.ToInt32((strExpRateCount.Length > 0 ? strExpRateCount : "0"));
                string strClassCount = main.WebString(dataItem["m_bgm_projectoperationexpense.m_bgm_projectexpense.m_bgm_mas_expense.class_count"].Text);
                int nClassCount = Convert.ToInt32((strClassCount.Length > 0 ? strClassCount : "0"));
                string strBgmExpSeq = main.WebString(dataItem["m_bgm_projectoperationexpense.m_bgm_projectexpense.bgm_exp_seq"].Text);

                //txtAmount.Attributes.Add("OnBlur", string.Format("txtBlur('{0}', '{1}', '{2}')"
                //    , txtAmount.ClientID, txtExchangeRate.ClientID, txtBathAmount.ClientID));
                //txtAmount.Attributes.Add("OnFocus", string.Format("txtFocus('{0}', '{1}', '{2}')"
                //    , txtAmount.ClientID, txtExchangeRate.ClientID, txtBathAmount.ClientID));
                //txtExchangeRate.Attributes.Add("OnBlur", string.Format("txtBlur('{0}', '{1}', '{2}')"
                //    , txtAmount.ClientID, txtExchangeRate.ClientID, txtBathAmount.ClientID));
                //txtExchangeRate.Attributes.Add("OnFocus", string.Format("txtFocus('{0}', '{1}', '{2}')"
                //    , txtAmount.ClientID, txtExchangeRate.ClientID, txtBathAmount.ClientID));
                //txtExchangeRate.Text = "1";
                txtAmount.Enabled = !(nExpRateCount > 0);
                cmdExpRate.Visible = nExpRateCount > 0;

                txtAmountVat.Attributes.Add("OnBlur", string.Format("txtVatBlur('{0}')"
                    , txtAmountVat.ClientID));
                txtAmountVat.Attributes.Add("OnFocus", string.Format("txtVatFocus('{0}')"
                    , txtAmountVat.ClientID));
                txtAmountTax.Attributes.Add("OnBlur", string.Format("txtTaxBlur('{0}')"
                    , txtAmountTax.ClientID));
                txtAmountTax.Attributes.Add("OnFocus", string.Format("txtTaxFocus('{0}')"
                    , txtAmountTax.ClientID));
                txtAmountVat.Text = "0";
                txtAmountTax.Text = "0";
                txtAmountVat.Enabled = false;
                txtAmountTax.Enabled = false;

                string strOpenWinFunction = (nClassCount > 0 && _strEventSeq == "16" ? "openWinExpRateEmp" : "openWinExpRate");
                cmdExpRate.OnClientClick = string.Format(strOpenWinFunction + "('{0}', '{1}', '{2}', '{3}', '{4}')"
                    , _strBgmSourceSeq, strBgmExpSeq, txtAmount.ClientID, null, null);
                cmdExpRate.Attributes.Add("InsertControl", txtAmount.ClientID);
            }
        }

        protected void chkVat_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox chkVat = (CheckBox)sender;
            GridTableCell cell = (GridTableCell)chkVat.Parent;
            RadNumericTextBox txtAmountVat = (RadNumericTextBox)cell.FindControl("txtAmountVat");
            RadNumericTextBox txtAmount = (RadNumericTextBox)((GridDataItem)cell.Parent)["amount"].FindControl("txtAmount");
            RadNumericTextBox txtExchangeRate = (RadNumericTextBox)((GridDataItem)cell.Parent)["exchange_rate"].FindControl("txtExchangeRate");
            bool bCheck = chkVat.Checked;

            if (bCheck)
            {
                //double dAmountVat = (txtAmountVat.Text != "" ? Convert.ToDouble(txtAmountVat.Text) : 0);
                double dPercentVat = (txtPercentVat.Text != "" ? Convert.ToDouble(txtPercentVat.Text) : 0);
                double dAmount = (txtAmount.Text != "" ? Convert.ToDouble(txtAmount.Text) : 0);
                double dExchangeRate = (txtExchangeRate.Text != "" ? Convert.ToDouble(txtExchangeRate.Text) : 0);
                double dAmountBath = dAmount * dExchangeRate;
                double dVat = (dAmountBath * dPercentVat) / 100;

                txtAmountVat.Text = dVat.ToString();
            }
            else
            {
                txtAmountVat.Text = "0";
            }

            txtAmountVat.Enabled = bCheck;
        }

        protected void chkTax_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox chkTax = (CheckBox)sender;
            GridTableCell cell = (GridTableCell)chkTax.Parent;
            RadNumericTextBox txtAmountVat = (RadNumericTextBox)cell.FindControl("txtAmountVat");
            RadNumericTextBox txtAmountTax = (RadNumericTextBox)cell.FindControl("txtAmountTax");
            RadNumericTextBox txtAmount = (RadNumericTextBox)((GridDataItem)cell.Parent)["amount"].FindControl("txtAmount");
            //RadNumericTextBox txtExchangeRate = (RadNumericTextBox)((GridDataItem)cell.Parent)["exchange_rate"].FindControl("txtExchangeRate");
            bool bCheck = chkTax.Checked;

            if (bCheck)
            {
                //double dAmountVat = (txtAmountVat.Text != "" ? Convert.ToDouble(txtAmountVat.Text) : 0);
                double dPercentTax = (txtPercentTax.Text != "" ? Convert.ToDouble(txtPercentTax.Text) : 0);
                double dAmount = (txtAmount.Text != "" ? Convert.ToDouble(txtAmount.Text) : 0);
                //double dExchangeRate = (txtExchangeRate.Text != "" ? Convert.ToDouble(txtExchangeRate.Text) : 0);
                //double dAmountBath = dAmount * dExchangeRate;
                double dVat = (txtAmountVat.Text != "" ? Convert.ToDouble(txtAmountVat.Text) : 0);
                double dTax = ((dAmount - dVat) * dPercentTax) / 100;

                txtAmountTax.Text = dTax.ToString();
            }
            else
            {
                txtAmountTax.Text = "0";
            }

            txtAmountTax.Enabled = bCheck;
        }

        public void Insert(string strMoneyReqSeq)
        {
            string strUserID = Session["EmpSeq"].ToString();
            DateTime dtNow = DateTime.Now;

            for (int i = 0; i < grdFimMoneyReqDtls.Items.Count; i++)
            {
                if (((RadNumericTextBox)grdFimMoneyReqDtls.Items[i]["amount"].FindControl("txtAmount")).Value > 0)
                {
                    // =================== แบบให้เลือกสกุลเงิน ========================
                    M_FIM_MoneyRequestDtls DtlsInfo = new M_FIM_MoneyRequestDtls();
                    string strBgmProjectExpSeq = main.WebString(grdFimMoneyReqDtls.Items[i]["m_bgm_projectoperationexpense.bgm_proj_oper_exp_seq"].Text);
                    //string strCurrencySeq = ((RadComboBox)grdFimMoneyReqDtls.Items[i]["currency_seq"].FindControl("ddlCurrencySeq")).SelectedValue;
                    Nullable<double> dAmount = ((RadNumericTextBox)grdFimMoneyReqDtls.Items[i]["amount"].FindControl("txtAmount")).Value;
                    //Nullable<double> dExchangeRate = ((RadNumericTextBox)grdFimMoneyReqDtls.Items[i]["exchange_rate"].FindControl("txtExchangeRate")).Value;
                    //Nullable<double> dBathAmount = dAmount * dExchangeRate;
                    Nullable<double> dAmountVat = ((RadNumericTextBox)grdFimMoneyReqDtls.Items[i]["vat"].FindControl("txtAmountVat")).Value;
                    Nullable<double> dAmountTax = ((RadNumericTextBox)grdFimMoneyReqDtls.Items[i]["tax"].FindControl("txtAmountTax")).Value;

                    DtlsInfo.money_req_seq = main.ConvertNullInt(strMoneyReqSeq);
                    DtlsInfo.bgm_proj_oper_exp_seq = main.ConvertNullInt(strBgmProjectExpSeq);
                    DtlsInfo.percent_vat = main.ConvertNullDouble(txtPercentVat.Text);
                    DtlsInfo.percent_tax = main.ConvertNullDouble(txtPercentTax.Text);
                    DtlsInfo.amount = dAmount;
                    //DtlsInfo.currency_seq = main.ConvertNullInt(strCurrencySeq);
                    //DtlsInfo.exchange_rate = dExchangeRate;
                    //DtlsInfo.bath_amount = dBathAmount;
                    //DtlsInfo.bath_amount_vat = dAmountVat;
                    //DtlsInfo.bath_amount_tax = dAmountTax;
                    DtlsInfo.job_site_seq = main.ConvertNullInt(_strJobsiteSeq);
                    DtlsInfo.created_by = main.ConvertNullInt(strUserID);
                    DtlsInfo.created_when = main.ConvertNullDateTime(dtNow);
                    mrd.Insert(DtlsInfo);
                }
            }
        }

        public void Update(string strMoneyReqSeq)
        {
            string strUserID = Session["EmpSeq"].ToString();
            DateTime dtNow = DateTime.Now;

            for (int i = 0; i < grdFimMoneyReqDtls.Items.Count; i++)
            {
                if (((RadNumericTextBox)grdFimMoneyReqDtls.Items[i]["amount"].FindControl("txtAmount")).Value > 0)
                {
                    // =================== แบบให้เลือกสกุลเงิน ========================
                    M_FIM_MoneyRequestDtls DtlsInfo = new M_FIM_MoneyRequestDtls();
                    string strMoneyReqDtlsSeq = main.WebString(grdFimMoneyReqDtls.Items[i]["money_req_dtls_seq"].Text);
                    string strBgmProjectExpSeq = main.WebString(grdFimMoneyReqDtls.Items[i]["m_bgm_projectoperationexpense.bgm_proj_oper_exp_seq"].Text);
                    //string strCurrencySeq = ((RadComboBox)grdFimMoneyReqDtls.Items[i]["currency_seq"].FindControl("ddlCurrencySeq")).SelectedValue;
                    Nullable<double> dAmount = ((RadNumericTextBox)grdFimMoneyReqDtls.Items[i]["amount"].FindControl("txtAmount")).Value;
                    //Nullable<double> dExchangeRate = ((RadNumericTextBox)grdFimMoneyReqDtls.Items[i]["exchange_rate"].FindControl("txtExchangeRate")).Value;
                    //Nullable<double> dBathAmount = dAmount * dExchangeRate;
                    Nullable<double> dAmountVat = ((RadNumericTextBox)grdFimMoneyReqDtls.Items[i]["vat"].FindControl("txtAmountVat")).Value;
                    Nullable<double> dAmountTax = ((RadNumericTextBox)grdFimMoneyReqDtls.Items[i]["tax"].FindControl("txtAmountTax")).Value;

                    DtlsInfo.money_req_seq = main.ConvertNullInt(strMoneyReqSeq);
                    DtlsInfo.bgm_proj_oper_exp_seq = main.ConvertNullInt(strBgmProjectExpSeq);
                    DtlsInfo.amount = dAmount;
                    //DtlsInfo.currency_seq = main.ConvertNullInt(strCurrencySeq);
                    //DtlsInfo.exchange_rate = dExchangeRate;
                    //DtlsInfo.bath_amount = dBathAmount;
                    //DtlsInfo.bath_amount_vat = dAmountVat;
                    //DtlsInfo.bath_amount_tax = dAmountTax;
                    DtlsInfo.job_site_seq = main.ConvertNullInt(_strJobsiteSeq);

                    if (strMoneyReqDtlsSeq == null || strMoneyReqDtlsSeq.Length == 0)
                    {
                        DtlsInfo.created_by = main.ConvertNullInt(strUserID);
                        DtlsInfo.created_when = main.ConvertNullDateTime(dtNow);
                        mrd.Insert(DtlsInfo);
                    }
                    else
                    {
                        DtlsInfo.money_req_dtls_seq = main.ConvertNullInt(strMoneyReqDtlsSeq);
                        DtlsInfo.updated_by = main.ConvertNullInt(strUserID);
                        DtlsInfo.updated_when = main.ConvertNullDateTime(dtNow);

                        if (dAmount != null || dAmount > 0)
                        {
                            mrd.Update(DtlsInfo);
                        }
                        else
                        {
                            mrd.Delete(DtlsInfo);
                        }
                    }
                }
            }
        }
    }
}